<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\library\WechatPhone;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['wxlogin', 'mobilelogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        // if (!Config::get('fastadmin.usercenter')) {
        //     $this->error(__('User center already closed'));
        // }

    }


    // /**
    //  * 会员登录
    //  *
    //  * @ApiMethod (POST)
    //  * @ApiParams (name="account", type="string", required=true, description="账号")
    //  * @ApiParams (name="password", type="string", required=true, description="密码")
    //  */
    // public function login()
    // {
    //     $code = $this->request->post('account');
    //     $password = $this->request->post('password');
    //     if (!$account || !$password) {
    //         $this->error(__('Invalid parameters'));
    //     }
    //     $ret = $this->auth->login($account, $password);
    //     if ($ret) {
    //         $data = ['userinfo' => $this->auth->getUserinfo()];
    //         $this->success(__('Logged in successful'), $data);
    //     } else {
    //         $this->error($this->auth->getError());
    //     }
    // }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function wxlogin()
    {
        $code = $this->request->post('code');
        $jscode = $this->request->post('jscode');
        if (!$code || !$jscode) {
            $this->error(__('Invalid parameters'));
        }
        $wechat = new WechatPhone(Config::get('site.wxapp_appid'), Config::get('site.wxapp_secret'));
        $openidResult = $wechat->getOpenid($jscode);
        if (!$openidResult) {
            $this->error(__('获取openid失败'));
        }
        $access_token = $wechat->getAccessToken();
        $phoneInfo = $wechat->decryptPhone($code, $access_token);
        if (!$phoneInfo || !isset($phoneInfo['phoneNumber'])) {
            $this->error(__('获取手机号失败'));
        }
        $mobile = $phoneInfo['phoneNumber'];
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status == 'disabled') {
                $this->error('账号已被禁用');
            }
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id, $openidResult['openid']);
        } else {
            $res = Db::name('patient')->where('userphone', $mobile)->find();
            if(!$res){
                $this->error(__('暂未注册，不可使用，请联系系统管理员！ 仅限企业内部人员使用'));
            }
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, [
                'openid'  => $openidResult['openid'],
                'unionid'  => isset($openidResult['unionid']) ? $openidResult['unionid'] : ''
            ]);
        }

        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $jscode = $this->request->post('jscode');
        if (!$mobile || !$captcha || !$jscode) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        $wechat = new WechatPhone(Config::get('site.wxapp_appid'), Config::get('site.wxapp_secret'));
        $openidResult = $wechat->getOpenid($jscode);
        if (!$openidResult) {
            $this->error(__('获取openid失败'));
        }

        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status == 'disabled') {
                $this->error('账号已被禁用');
            }

            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id, $openidResult['openid']);
        } else {
            $res = Db::name('patient')->where('userphone', $mobile)->find();
            if(!$res){
                $this->error(__('暂未注册，不可使用，请联系系统管理员！ 仅限企业内部人员使用'));
            }
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, [
                'openid'  => $openidResult['openid'],
                'unionid'  => isset($openidResult['unionid']) ? $openidResult['unionid'] : ''
            ]);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取用户信息
     *
     * @ApiMethod (POST)
     */
    public function getuserinfo()
    {
        $user = $this->auth->getUserinfo();
        $this->success('', ['user' => $user]);
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=false, description="头像地址")
     * @ApiParams (name="nickname", type="string", required=false, description="昵称")
     * @ApiParams (name="gender", type="string", required=false, description="性别:1=男,0=女")
     * @ApiParams (name="birthday", type="string", required=false, description="生日：YYYY-MM-DD")
     * @ApiParams (name="idcardnumber", type="string", required=false, description="身份证")
     * @ApiParams (name="address", type="string", required=false, description="居住地")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $nickname = $this->request->post('nickname');
        $birthday = $this->request->post('birthday');
        $gender = $this->request->post('gender');
        $address = $this->request->post('address');
        $idcardnumber = $this->request->post('idcardnumber');

        if (!empty($avatar)) {
            $user->avatar = $avatar;
        }
        if (!empty($birthday)) {
            $user->birthday = $birthday;
        }
        if (!empty($gender)) {
            $user->gender = $gender;
        }
        if (!empty($address)) {
            $user->address = $address;
        }
        if (!empty($idcardnumber)) {
            $user->idcardnumber = $idcardnumber;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }

        $user->save();
        $this->success();
    }

    /**
     * 充值
     */
    public function rechargeSubmit(){
        $recharge_package_id = $this->request->post('recharge_package_id');
        if (empty($recharge_package_id)) {
            $this->error(__('Invalid parameters'));
        }
        $user = $this->auth->getUser();
        if ($user->role != 30) {
            $this->error('该用户暂不支持此操作');
        }
        $rechargePackageInfo = \app\api\model\matketing\RechargePackage::get($recharge_package_id);
        if(empty($rechargePackageInfo)){
            $this->error('充值套餐不存在');
        }
        $model = new \app\api\model\matketing\RechargePackageOrder();
        $model->user_id = $this->auth->id;
        $model->money = $rechargePackageInfo->money;
        $model->gift_money = $rechargePackageInfo->gift_money;
        $model->status ='0';
        $model->order_sn = createOrdersn($user->id,'R');
        $model->save();


        $pay = new \addons\epay\library\Service();
        $request = request();
        $notifyurl =  $request->root(true) . '/api/notifyx/notifyxRecharge/paytype/wechat';
        $result = $pay->submitOrder([
            'amount'    => $model->money,
            'orderid'   => $model->order_sn,
            'type'      => 'wechat',
            'title'     => "充值套餐：充{$model->money}赠{$model->gift_money}",
            'notifyurl' => $notifyurl,
            'returnurl' => '',
            'method'    => 'miniapp',
            'openid'    => $user->openid,
            'custom'    => [],
        ]);

        $this->success('', $result);

    }


    /**
     * 获取充值记录
     */
    public function getRechargeRecord()
    {
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $between = $this->request->post('between/a',[]);
        
        $model = new \app\api\model\matketing\RechargePackageOrder();
        $where = [
            'user_id' => $this->auth->id,
            'status' => 1
        ];
        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }

        $data = $model::where($where)->with(['user'])->order('createtime', 'desc')->paginate($limit, false, ['page' => $page]);
        $this->success('', $data);
    }


    /**
     * 获取用户充值总额,购买项目总额,患者数量
     */
    public function getUserRechargeTotal()
    {
        $between = $this->request->post('between/a',[]);

        $user = $this->auth->getUser();
        $model = new \app\api\model\matketing\RechargePackageOrder();
        $where = [
            'user_id' => $user->id,
            'status' => 1
        ];
        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }
        $rechargeMoney = $model::where($where)->sum('money'); 
        $rechargeGiftMoney = $model::where($where)->sum('gift_money'); 

        $model = new \app\api\model\order\OrderMaster();
        $where = [
            'user_id' => $user->id,
            'pay_status' => 1
        ];
        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }
        $goodsMoney = $model::field('price')->where($where)->sum('price');

        $model = new \app\api\model\Patient();
        $where = [
            'doctor_id'=>$user->id,
        ];
        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }
        $patientCount = $model::where($where)->count('id');

        $this->success('', ['rechargeMoney' => $rechargeMoney + $rechargeGiftMoney, 'goodsMoney' => $goodsMoney,'patientCount'=>$patientCount]);
    }

    /**
     * 获取项目支出记录
     */
    public function getGoodsExpenseRecord()
    {
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $between = $this->request->post('between/a',[]);
        $title = $this->request->post('title','');

        $model = new \app\api\model\order\OrderMaster();
        $where = [
            'user_id' => $this->auth->id,
            'pay_status' => 1
        ];

        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }
        $data = $model::field('id,out_trade_no,price,pay_time')->where($where)->where(function($query) use ($title){
            if ($title){
                $query->where('out_trade_no', 'like', '%'.$title.'%')
                        ->whereOr('username', 'like', '%'.$title.'%')
                        ->whereOr('userphone', 'like', '%'.$title.'%');
            }
        })->with(['ordergoodstitle'])->order('pay_time', 'desc')->paginate($limit, false, ['page' => $page]); 
        foreach ($data as $key => $value) {
            $titles = array_column($value['ordergoodstitle'], 'title');
            $data[$key]['title'] = implode(',', $titles);
        }
        $total = $model::where($where)->sum('price');
        $this->success('', ['data' => $data, 'totalMoney' => $total]);
    }

    /**
     * 患者列表
     */
    public function patientList()
    {
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $between = $this->request->post('between/a',[]);
        $title = $this->request->post('title', '');
        
        $model = new \app\api\model\Patient();
        $where = [
            'doctor_id' => $this->auth->id,
        ];
        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }
        $subQuery = Db::name('order_master')
            ->field('SUM(price) as order_money,userphone')
            ->group('userphone')
            ->where('user_id', $this->auth->id)
            ->where('pay_status','=',1)
            ->buildSql();
        $data = $model::alias("patient")->field("patient.*, IFNULL(order_master.order_money, 0) as order_money")
            ->join([$subQuery=>'order_master'], "order_master.userphone = patient.userphone","LEFT")
            ->where($where)->where(function($query) use ($title){
                if ($title){
                    $query->where('patient.username', 'like', '%'.$title.'%')
                        ->whereOr('patient.userphone', 'like', '%'.$title.'%');
                }
            })->order('createtime', 'desc')->paginate($limit, false, ['page' => $page]);
        foreach ($data as $key => $value) {
            $data[$key]['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
        }
        $this->success('', $data);
    }

    /**
     * 金额明细
     */
    public function moneyDetail()
    { 
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $between = $this->request->post('between/a',[]);

        $model = new \app\api\model\UserAccountLog();
        $where = [
            'user_id' => $this->auth->id,
        ];
        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }
        $data = $model::where($where)->order('createtime', 'desc')->paginate($limit, false, ['page' => $page]);
        $this->success('', $data);
    }


    /**
     * 用户反馈
     */
    public function feedback()
    { 
        $content = $this->request->post('content', '');
        $message_type_id  = $this->request->post('message_type_id', '');
        if (!$message_type_id) {
            $this->error(__('请选择留言类型'));
        }
        if (!$content) {
            $this->error(__('请填写留言内容'));
        }
        $user = $this->auth->getUser();
        $model = new \app\api\model\message\MessageBoard();
        if($user->role == 30){
            if(!$user->hospital_id){
                $this->error(__('请先绑定医院'));
            }
            $hospital = \app\api\model\hospital\Hospital::where('id', $user->hospital_id)->find();
            $model->sale_id = $hospital->user_id;
        }
        $model->user_id = $this->auth->id;
        $model->message_type_id = $message_type_id;
        $model->source = $user->role;
        $model->content = $content;
        $model->save();

        $this->success('提交成功');
    }

    /**
     * 获取用户反馈列表

     */
    public function feedbackList()
    { 
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $between = $this->request->post('between/a',[]);

        $model = new \app\api\model\message\MessageBoard();
        $where = [
            'user_id' => $this->auth->id,
        ];
        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }
        $data = $model::where($where)->with(['messageType'])->order('createtime', 'desc')->paginate($limit, false, ['page' => $page]);
        $this->success('', $data);
    }

}
